package com.tvb.comm.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class WeatherUtil {
	static Log log = LogFactory.getLog(WeatherUtil.class.getName());

	public static String getHostCode() {
		String hostCode = "";
		String url = "http://www.weather.com.cn/data/cityinfo/101010100.html";
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		System.out.println(method.getParams());
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		 new DefaultHttpMethodRetryHandler(3, false));
		 client.getHostConfiguration().setProxy("10.101.1.6", 80);
		 Credentials credentials = new
		 UsernamePasswordCredentials("_SSO_T_00105", "t00105@sso");
		 client.getState().setCredentials(AuthScope.ANY, credentials);
		try {
			int statusCode = client.executeMethod(method);
			if (statusCode == HttpStatus.SC_OK) {
				BufferedInputStream bis = new BufferedInputStream(
						method.getResponseBodyAsStream());
				byte[] bytes = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int count = 0;
				while ((count = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, count);
				}
				byte[] strByte = bos.toByteArray();
				hostCode = new String(strByte, 0, strByte.length, "UTF-8");
				bos.close();
				bis.close();
			} else {
				log.info(("HostCode 加载失败 状态: " + method.getStatusLine()));
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return hostCode;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(WeatherUtil.getHostCode());
	}
}
